﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Linq;

namespace Pay.Service.Service {
    public class MarketingAccountService : ServiceBase, IMarketingAccountService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IShopInfoService _iShopInfoService;
        private IMerchantService _iMerchantService;
        public MarketingAccountService(IUnitOfWork iUnitOfWork, IShopInfoService iShopInfoService, IMerchantService iMerchantService) : base(iUnitOfWork) {
            this._iUnitOfWork = iUnitOfWork;
            _iShopInfoService = iShopInfoService;
            _iMerchantService = iMerchantService;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="login_model"></param>
        /// <returns></returns>
        public marketing_user_dto UserLogin(marketing_login_model login_model) {
            var oem = context.Merchants.FirstOrDefault(c => c.MerchantNo == t_RequestMethod.merchant_no);
            var merchant = context.Merchants.FirstOrDefault(c => c.Mobile == login_model.username
                            && ((c.IsOEM == false && c.OemId == oem.Id) || c.MerchantNo == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO));
            if (merchant == null)
                throw new ServerErrorException("账号或密码错误");
            else if (merchant != null && merchant.Password != WebHelper.GetPasswrodWithTwiceEncode(login_model.password, merchant.PasswordSalt))
                throw new ServerErrorException("账号或密码错误");
            if (merchant.MerchantNo != t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {//非系统默认账号
                if (merchant.UserType != UserType.tokenMaker && merchant.UserType != UserType.tokenNodeMall && merchant.UserType != UserType.tokenCountyAgent && merchant.UserType != UserType.tokenCityAgent)
                    throw new ServerErrorException("账号未开通权限");
                if (merchant.Disabled == true)
                    throw new ServerErrorException("当前账号已被冻结");
                if (!context.AuthInfos.Exist(o => o.MerchantId == merchant.Id && o.Status == CertifyStatus.Auth))
                    throw new ServerErrorException("您的账号未实名，请先在拓垦内完成实名认证");
                if (!context.AuthInfos.Exist(o => o.MerchantId == merchant.Id && o.Status == CertifyStatus.Auth))
                    throw new ServerErrorException("您的账号未实名，请先在拓垦内完成实名认证");
            }
            bool is_has_receivable = context.MerchantReceivables.Exist(o => o.MerchantId == merchant.Id);
            marketing_user_dto result = new marketing_user_dto() { id = merchant.Id, user_name = merchant.Name, mobile = merchant.Mobile, user_type = merchant.UserType, is_has_receivable = is_has_receivable };

            return result;
        }

        /// <summary>
        /// 获取合伙人系统用户登录信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public marketing_user_dto_ex GetMarketingUserInfo(long userId) {
            var merchant = context.Merchants.FirstOrDefault(c => c.Id == userId).ToDtoObject<merchant_dto>();

            bool is_has_receivable = context.MerchantReceivables.Exist(o => o.MerchantId == merchant.id);
            marketing_user_dto_ex result =
                new marketing_user_dto_ex() { id = merchant.id, user_name = merchant.name, mobile = merchant.mobile, user_type = merchant.usertype, is_has_receivable = is_has_receivable, disabled = merchant.disabled };

            return result;
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool ChangePassword(marketing_change_pwd_model model, long merchantId) {
            if (string.IsNullOrEmpty(model.old_pwd))
                throw new ServerErrorException("原密码不能为空");
            if (string.IsNullOrEmpty(model.new_pwd))
                throw new ServerErrorException("新密码不能为空");
            var manager = context.Merchants.FirstOrDefault(c => c.Id == merchantId);
            if (manager.Password != WebHelper.GetPasswrodWithTwiceEncode(model.old_pwd, manager.PasswordSalt))
                throw new ServerErrorException("原密码错误");

            manager.Password = WebHelper.GetPasswrodWithTwiceEncode(model.new_pwd, manager.PasswordSalt);
            _iUnitOfWork.Commit();
            return true;
        }

        #region 供应商PC
        /// <summary>
        /// 供应商用户登录
        /// </summary>
        /// <param name="login_model"></param>
        /// <returns></returns>
        public marketing_supplier_dto SupplierLogin(marketing_login_model login_model) {
            var oem = context.Merchants.FirstOrDefault(c => c.MerchantNo == t_RequestMethod.merchant_no);
            var merchant = context.Merchants.FirstOrDefault(c => c.Mobile == login_model.username
                            && ((c.IsOEM == false && c.OemId == oem.Id) || c.MerchantNo == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO));
            if (merchant == null)
                throw new ServerErrorException("账号或密码错误");
            else if (merchant != null && merchant.Password != WebHelper.GetPasswrodWithTwiceEncode(login_model.password, merchant.PasswordSalt))
                throw new ServerErrorException("账号或密码错误");

            if (merchant.Disabled == true)
                throw new ServerErrorException("当前账号已被冻结");
            if (!context.AuthInfos.Exist(o => o.MerchantId == merchant.Id && o.Status == CertifyStatus.Auth))
                throw new ServerErrorException("您的账号未实名，请先在拓垦内完成实名认证");
            if (merchant.IsSupplier == false)
                throw new ServerErrorException("账号未开通权限");

            var shop = _iShopInfoService.GetShopById(merchant.Id);
            if (shop != null && shop.id > 0 && shop.is_disabled == true)
                throw new ServerErrorException("您的商城账号已被冻结");

            marketing_supplier_dto result = new marketing_supplier_dto()
            { id = merchant.Id, user_name = merchant.Name, mobile = merchant.Mobile, user_type = merchant.UserType, is_has_shop = (shop != null && shop.id > 0) ? true : false ,
                shop_name = shop != null ?  shop.shop_name :"",  disabled  = false};

            return result;
        }

        /// <summary>
        /// 获取供应商系统用户登录信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public marketing_supplier_dto GetMarketingSupplier(long userId) {
            var merchant = _iMerchantService.Get(userId);
            var shop = _iShopInfoService.GetShopById(userId);

            marketing_supplier_dto result =
                new marketing_supplier_dto() { id = merchant.id, user_name = merchant.name, mobile = merchant.mobile, user_type = merchant.usertype,
                    is_has_shop = (shop != null && shop.id > 0) ? true : false,
                    shop_name = shop != null ? shop.shop_name : "",
                    disabled = (merchant.disabled || (shop != null && shop.id > 0 && shop.is_disabled)) };

            return result;
        }
        #endregion
    }
}
